package com.jp.knowledge.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Gravity;
import android.view.KeyboardShortcutGroup;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.adapter.HeadItemAdapter;
import com.jp.knowledge.adapter.OnItemListerner;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.callback.ItemDragHelperCallback;
import com.jp.knowledge.comm.JpApplication;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.util.ResultSubscriber;

import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;

/**
 * Created by jiayen on 17/6/6.
 */

public class HeadlineDragDialog extends Dialog implements View.OnClickListener {
    private View conentView;
    private JpApplication application;

    private Context mContext;
    //拖动gridView
    private RecyclerView sortView;
    private HeadItemAdapter headItemAdapter;
    private TextView sureBtn;//确定按钮
    private HeadItemAdapter adapter;

    private TextView levelPrimary;
    private TextView levelIntermediate;
    private TextView levelAdvanced;

    private ComPopuWindow.DragItemHelper dragItemHelper;
    private List<HeadLine> list;

    private OnItemListerner onItemListerner;

    public HeadlineDragDialog(Context context) {
        this(context,R.style.custom_idalgo);
    }

    public void setApplication(JpApplication application){
        this.application = application;
    }


    public void setDragItemHelper(ComPopuWindow.DragItemHelper dragItemHelper) {
        this.dragItemHelper = dragItemHelper;
    }

    public HeadlineDragDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.mContext=context;
    }

    protected HeadlineDragDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.mContext=context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        conentView = getLayoutInflater().inflate(R.layout.drag_headline_sort, null);
        setContentView(conentView);
        setCanceledOnTouchOutside(true);//点空白不消失
        Window dialogWindow = this.getWindow();
        dialogWindow.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width= DensityUtil.getScreenWidth()-30;
        lp.height=  WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
        init();
    }

    private void init() {
        sureBtn = (TextView) conentView.findViewById(R.id.sure);
        sortView = (RecyclerView) conentView.findViewById(R.id.activity_sort_head);
        sureBtn.setOnClickListener(this);

        levelPrimary = (TextView) conentView.findViewById(R.id.level_primary);
        levelIntermediate = (TextView) conentView.findViewById(R.id.level_intermediate);
        levelAdvanced = (TextView) conentView.findViewById(R.id.level_advanced);

        levelPrimary.setTag(1);
        levelIntermediate.setTag(2);
        levelAdvanced.setTag(3);

        levelPrimary.setOnClickListener(this);
        levelIntermediate.setOnClickListener(this);
        levelAdvanced.setOnClickListener(this);

        bindViewData();
    }


    /**
     * 绑定数据
     */
    private void bindViewData() {
        adapter = new HeadItemAdapter(mContext,list);
        adapter.setItemListerner(onItemListerner);
        adapter.setDragItemHelper(dragItemHelper);
        GridLayoutManager layoutMannager = new GridLayoutManager(mContext, 3, LinearLayoutManager.VERTICAL, false);

        sortView.setLayoutManager(layoutMannager);
        sortView.setItemAnimator(new DefaultItemAnimator());
        sortView.setAdapter(adapter);
        initItemDrag();
    }


    public List<HeadLine> getHeadLine(){
        return adapter.getData();
    }
    /**
     * 初始化拖拽
     */
    private void initItemDrag() {
        ItemDragHelperCallback itemDragHelperCallback = new ItemDragHelperCallback(adapter);
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(itemDragHelperCallback);
        itemTouchHelper.attachToRecyclerView(sortView);
        adapter.setItemTouchHelper(itemTouchHelper);
        adapter.setItemDragHelperCallback(itemDragHelperCallback);
    }

    public void updateData(List<HeadLine> list){//刷新数据
        if(list==null) list = new ArrayList<>();
        this.list=list;
        adapter.update(list);
//        adapter.notifyDataSetChanged();
    }

    @Override
    public void show() {
        super.show();
        UserData userData = application.getUserData();
        setLevelBtn(userData == null ? 1 : userData.getSkillLevel());
    }

    private void setLevelBtn(int level){
        levelPrimary.setBackground(mContext.getResources().getDrawable(R.drawable.btn_rbg_gray));
        levelPrimary.setTextColor(mContext.getResources().getColor(R.color.gray_deep));
        levelIntermediate.setBackground(mContext.getResources().getDrawable(R.drawable.btn_rbg_gray));
        levelIntermediate.setTextColor(mContext.getResources().getColor(R.color.gray_deep));
        levelAdvanced.setBackground(mContext.getResources().getDrawable(R.drawable.btn_rbg_gray));
        levelAdvanced.setTextColor(mContext.getResources().getColor(R.color.gray_deep));
        TextView btn = null;
        if(level == 1)
            btn = levelPrimary;
        else if(level == 2)
            btn = levelIntermediate;
        else if(level == 3)
            btn = levelAdvanced;
        if(btn == null)
            return;
        btn.setBackground(mContext.getResources().getDrawable(R.drawable.btn_blue));
        btn.setTextColor(mContext.getResources().getColor(R.color.white));
    }

    public List<HeadLine> getList() {
        return list;
    }

    @Override
    public void onClick(View view) {
        if(view == sureBtn) {
            this.dismiss();
            return;
        }
        if(view != levelPrimary && view != levelIntermediate && view != levelAdvanced)
             return;
        setLevelBtn((int) view.getTag());
        JsonObject param = new JsonObject();
        param.addProperty("skillLevel", (int) view.getTag());
        HttpHelper.getInstance(mContext).updateUserInfo(param, (int) view.getTag(), new ResultSubscriber.OnResultListener() {
            @Override
            public void onStart(int requestType) {}
            @Override
            public void onCompleted(int requestType) {}
            @Override
            public void onError(int requestType) {}
            @Override
            public void onNext(IModel data, int requestType) {
                if(data.getErrcode() == 0){
                    UserData userData = application.getUserData();
                    if(userData != null)
                        userData.setSkillLevel(requestType);
                    LocalBroadcastManager.getInstance(mContext)
                            .sendBroadcast(new Intent(LocalBroadCast.USER_DATA_CHANGE));
                }
            }
        });
    }

    @Override
    public void onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {

    }

    @Override
    public void setOnDismissListener(OnDismissListener listener) {
        super.setOnDismissListener(listener);

        //缓存   岗位知识

        //缓存  headline
    }
}
